<template>
	<view class="content">
		<!-- 导航栏 -->
		<u-navbar title-color="#fff" back-icon-color="#ffffff" is-back="true" :background="background" :back-text-style="{ color: '#fff' }"
		 title="内存管理" back-icon-name="nav-back">
			<view class="navbar-right" slot="right">
				<view class="dot-box right-item fo-white paddlr20">
					<!-- <text class="cuIcon-refresh fo-46 mr20" @click="AsyncData"></text> -->
					<!-- <text class="cuIcon-roundadd fo-46" @click="onAdd"></text> -->
				</view>
			</view>
		</u-navbar>
		
		
		<text style="color:red;">提示：长按可删除！警告：不要随意删除文件会导致整个app运行奔溃</text>
		<view class="title" style="color: gray; width: 100%;text-align: justify;
		text-justify: newspaper;word-break: break-all;">完整路径:{{root}}</view>
		<view class="Dir-item"  @click="onPre" >返回上一级</view>
		<view class="Dir-item" v-for="(i,j) in DIR_LIST" :key='j' @click="onNext(i.fullPath)" @touchstart='itemTouchStart(i.fullPath)' @touchend='itemTouchEnd'>
			<template v-if="!i.isFile">
				<image class="Dir-item-icon" src="../../../static/img/home/NewFolder.png"></image>
			</template>
			<template v-else>
				<image class="Dir-item-icon" v-if="comIsImg('img', i.name)" src="../../../static/img/home/UploadPictures.png"></image>
				<image class="Dir-item-icon" v-if="comIsImg('video', i.name)" src="../../../static/img/home/UploadVideo.png"></image>
				<image class="Dir-item-icon" v-if="comIsImg('audio', i.name)" src="../../../static/img/home/UploadAudio.png"></image>
				<image class="Dir-item-icon" v-if="comIsImg('doc', i.name)" src="../../../static/img/home/UploadDoc.png"></image>
				<image class="Dir-item-icon" v-if="comIsImg('PPT', i.name)" src="../../../static/img/home/ppt.png"></image>
				<image class="Dir-item-icon" v-if="comIsImg('HTML', i.name)" src="../../../static/img/home/HTML.png"></image>
				<image class="Dir-item-icon" v-if="comIsImg('CSS', i.name)" src="../../../static/img/home/CSS.png"></image>
				<image class="Dir-item-icon" v-if="comIsImg('JS', i.name)" src="../../../static/img/home/JS.png"></image>
				<image class="Dir-item-icon" v-if="comIsImg('Vue', i.name)" src="../../../static/img/home/Vue.png"></image>
				<image class="Dir-item-icon" v-if="comIsImg('JSON', i.name)" src="../../../static/img/home/JSON.png"></image>
				<image class="Dir-item-icon" v-if="comIsImg('MD', i.name)" src="../../../static/img/home/MD.png"></image>
				<image class="Dir-item-icon" v-if="comIsImg('PDF', i.name)" src="../../../static/img/home/pdf.png"></image>
				<image class="Dir-item-icon" v-if="comIsImg('yasuo', i.name)" src="../../../static/img/home/yasuo.png"></image>
				<image class="Dir-item-icon" v-if="$tool.getFileType(i.name) == 'adu'" src="../../../static/img/home/UploadDoc.png"></image>
			</template>
			<view class="Dir-item-txt">
				<text style="font-weight: 600; font-size: 30rpx;">{{i.name}}</text>
				<text class="fo-gray mt10" v-if="!i.isFile">文件夹:{{i.dir}}项    文件:{{i.file}}项</text>
				<view class="fo-gray mt10 flex just-spa-bet">
					<text>{{$tool.comFileSize(i.size)}}</text>
					<text style="color: gray;">{{i.modifiTime | formatDate}}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	let timers = null
	export default {
		data() {
			return {
				background: {
					background: '#87ceeb'
				},
				
				DIR_LIST:[
					{name:'PUBLIC_DOCUMENTS',size:0,file:0,dir:0,modifiTime:new Date(),fullPath:null,isFile:false},
					{name:'PUBLIC_DOWNLOADS',size:0,file:0,dir:0,modifiTime:new Date(),fullPath:null,isFile:false},
					{name:'PRIVATE_WWW',size:0,file:0,dir:0,modifiTime:new Date(),fullPath:null,isFile:false},
					{name:'PRIVATE_DOC',size:0,file:0,dir:0,modifiTime:new Date(),fullPath:null,isFile:false}
				],
				root:""
			}
		},
		computed:{
			// 计算是否是图片资源
			comIsImg() {
				return (type, str) => {
					if (type == 'img') {
						return this.$tool.ImgTypes(this.$tool.getFileType(str));
					} else if (type == 'video') {
						return this.$tool.ViodeoTypes(this.$tool.getFileType(str));
					} else if (type == 'doc') {
						return this.$tool.DocTypes(this.$tool.getFileType(str));
					} else if (type == 'audio') {
						return this.$tool.AudioTypes(this.$tool.getFileType(str));
					} else if (type == 'HTML') {
						return this.$tool.getFileType(str) == 'html';
					} else if (type == 'CSS') {
						return this.$tool.getFileType(str) == 'css';
					} else if (type == 'JS') {
						return this.$tool.getFileType(str) == 'js';
					} else if (type == 'Vue') {
						return this.$tool.getFileType(str) == 'vue';
					} else if (type == 'JSON') {
						return this.$tool.getFileType(str) == 'json';
					} else if (type == 'MD') {
						return this.$tool.getFileType(str) == 'md';
					} else if (type == 'PDF') {
						return this.$tool.getFileType(str) == 'pdf';
					} else if (type == 'PPT') {
						return this.$tool.PPTTypes(this.$tool.getFileType(str));
					} else if (type == 'yasuo') {
						return this.$tool.yasuoTypes(this.$tool.getFileType(str));
					}
				};
			}
		},
		filters:{
			formatDate(obj, type) {
				let D = {};
				var type = type || 'YYYYMMMDDHHMMSS';
				var sign = sign || '-';
				Object.defineProperties(D, {
					'year': {
						value: null,
						writable: true
					},
					'month': {
						value: null,
						writable: true
					},
					'date': {
						value: null,
						writable: true
					},
					'hour': {
						value: null,
						writable: true
					},
					'minute': {
						value: null,
						writable: true
					},
					'second': {
						value: null,
						writable: true
					},
				});
				D['year'] = obj.getFullYear();
				D['month'] = (obj.getMonth() + 1) >= 10 ? (obj.getMonth() + 1) : "0" + (obj.getMonth() + 1);
				D['date'] = obj.getDate() >= 10 ? obj.getDate() : "0" + obj.getDate();
				D['hour'] = obj.getHours() >= 10 ? obj.getHours() : "0" + obj.getHours();
				D['minute'] = obj.getMinutes() >= 10 ? obj.getMinutes() : "0" + obj.getMinutes();
				D['second'] = obj.getSeconds() >= 10 ? obj.getSeconds() : "0" + obj.getSeconds();
				if (type == 'YYYYMMMDD') {
					return "" + D.year + sign + D.month + sign + D.date
				}
				if (type == 'HHMMSS') {
					return "" + D.hour + ":" + D.minute + ":" + D.second
				}
				if (type == 'YYYYMMMDDHHMMSS') {
					return "" + D.year + sign + D.month + sign + D.date + " " + D.hour + ":" + D.minute + ":" + D.second
				}
			}
		},
		onLoad() { 
			let culue = {
				'PUBLIC_DOCUMENTS':plus.io.PUBLIC_DOCUMENTS, // 程序公用文档目录常量
				'PUBLIC_DOWNLOADS':plus.io.PUBLIC_DOWNLOADS, // 程序公用下载目录常量
				'PRIVATE_WWW':plus.io.PRIVATE_WWW, // 应用运行资源目录常量
				'PRIVATE_DOC':plus.io.PRIVATE_DOC  // 应用私有文档目录常量
			}
			for(let i=0;i<this.DIR_LIST.length;i++){
				this.INIT_ROOT_DIR(culue[this.DIR_LIST[i].name],this.DIR_LIST[i])
			}
			
			plus.io.requestFileSystem(culue['PRIVATE_WWW'],async(fs)=> {
				this.root = fs.root.fullPath.split('/').slice(0,-4).join('/')
			}, function(e) {
				plus.nativeUI.alert("Request file system failed:" + e.message);
			});
		},
		methods: {
			// 初始化
			INIT_ROOT_DIR(URL,item){
				let self = this
				plus.io.requestFileSystem(URL,async(fs)=> {
					let FileInfo = await this.GetFileInfo_for_URL(fs.root.fullPath)
					if(FileInfo.status){
						item['name'] = FileInfo.name
						item['size'] = FileInfo.size
						item['file'] = FileInfo.fileCount
						item['dir'] = FileInfo.directoryCount
						item['modifiTime'] = FileInfo.modifiTime
						item['fullPath'] = FileInfo.fullPath
						item['isFile'] = FileInfo.isFile
					}
				}, function(e) {
					plus.nativeUI.alert("Request file system failed:" + e.message);
				});
			},
			// 文件列表信息修改
			async ChangeDIR_LIST(URL,item){
				// 获取该路径的信息
				let FileInfo = await this.GetFileInfo_for_URL(URL)
				// item['name'] = FileInfo.name
				item['size'] = FileInfo.size
				item['file'] = FileInfo.fileCount
				item['dir'] = FileInfo.directoryCount
				item['modifiTime'] = FileInfo.modifiTime
				item['isFile'] = FileInfo.isFile
			},
			// 传入绝对路径 返回该文件/目录信息
			GetFileInfo_for_URL(URL) {
				/*
					status:是否获取成功,
					name:文件名字/文件夹名字
					size:文件大小
					file:文件的数量
					dir:子目录的数量
					modifiTime:操作时间
					fullPath:绝对路径
					isFile:是否是文件
					entry:目录对象
				*/
				return new Promise((resolve,reject)=>{
					plus.io.resolveLocalFileSystemURL(URL,(entry)=>{
						entry.getMetadata((metadata)=>{
							resolve({
								status:true,
								name:entry.name || (/\/$/g).test(URL)?  URL.split('/').slice(-2)[0]:URL.split('/').slice(-1)[0],
								size:metadata.size,
								fileCount:metadata.fileCount,
								directoryCount:metadata.directoryCount,
								modifiTime:metadata.modificationTime,
								fullPath:URL,
								isFile:entry.isFile,
								entry
							})
						}, (e)=>{
							plus.nativeUI.alert("该目录/文件不存在~：" + e.message);
							resolve({status:false})
						}, true);
					},(e)=>{
						plus.nativeUI.alert("该目录/文件不存在~：" + e.message);
						resolve({status:false})
					})
				})
			},
			// 下一级
			async onNext(URL){
				// 获取该路径的信息
				let FileInfo = await this.GetFileInfo_for_URL(URL)
				// 该目录/文件不存在
				if(!FileInfo.status) return
				// 如果是文件夹且该目录下没有文件或目录
				if(!FileInfo.isFile && FileInfo.directoryCount===0 && FileInfo.fileCount===0){
					uni.showModal({
					    title: '提示',
					    content: '该目录下暂无文件和文件夹',
						showCancel:false
					});
					return
				}
				// 如果是文件
				if(FileInfo.isFile){
					plus.runtime.openFile(FileInfo.fullPath, {}, (e)=>{
						plus.nativeUI.alert("无法打开此文件：" + e.message);
					});
					return
				}
				this.DIR_LIST = [] // 文件/文件夹列表置空
				this.root = URL // 重新赋值当前的绝对路径
				var dirReader = FileInfo.entry.createReader();
				dirReader.readEntries((entries)=>{
					entries.forEach(i=>{
						this.DIR_LIST.push({
							name:i.name,
							size:0,file:0,dir:0,modifiTime:0,
							isDirectory:i.isDirectory?true:false,
							fullPath:i.fullPath,
							isFile:true
						})
					})
					for(let i=0;i<this.DIR_LIST.length;i++){
						// 改变值
						this.ChangeDIR_LIST(this.DIR_LIST[i].fullPath,this.DIR_LIST[i])
					}
				},(e)=>{
					console.log("Read directory " + item.id + " failed: " + e.message);
				});
			},
			// 上一级
			onPre(){
				if(!this.root){
					return uni.showToast({
						title: '当前已是最高路径',
						icon:'none'
					});
				}
				this.root = this.root.split('/').slice(0,-1).join('/')
				this.onNext(this.root)
			},
			// item条长按开始
			itemTouchStart(e){
				if(timers) return
				timers = setTimeout(()=>{
					clearTimeout(timers)
					timers = null
					// delID = e
					// this.YModalTxt = '是否删除该上传任务记录？'
					// this.YModalShow = true
					
					uni.showModal({
					    title: '提示',
					    content: '是否删除该文件',
					    success: async (res)=> {
					        if (res.confirm) {
					            console.log('用户点击确定',e);
								let FileInfo = await this.GetFileInfo_for_URL(e)
								if(!FileInfo.status) return plus.nativeUI.alert("获取文件/目录错误：" + e.message);
								if(FileInfo.isFile){
									FileInfo.entry.remove((entry)=>{
										uni.showToast({
											title: '文件删除成功~',
											icon:'none'
										});
									},(e)=>{
										plus.nativeUI.alert("文件删除失败~：" + e.message);
									})
								}else{
									let URL = FileInfo.fullPath
									let predir =  (/\/$/g).test(URL)?  URL.split('/').slice(0,-2).join('/'):URL.split('/').slice(0,-1).join('/')
									let delDirName = (/\/$/g).test(URL)?  URL.split('/').slice(-2)[0]:URL.split('/').slice(-1)[0]
									console.log(predir,delDirName)
									
									// 递归删除
									FileInfo.entry.removeRecursively((entry)=>{
										uni.showToast({
											title: '文件删除成功~',
											icon:'none'
										});
									},(e)=>{
										plus.nativeUI.alert("文件删除失败~：" + e.message);
									})
									if(delDirName==='documents' || delDirName==='downloads'){
										// 创建文件夹
										FileInfo = await this.GetFileInfo_for_URL(predir)
										FileInfo.entry.getDirectory( delDirName,  {create:true,exclusive:false}, function( dir ){
											console.log("Directory Entry Name: " + dir.name);
										}, function (e) {
											console.log( e.message );
										} );
									}
								}
					        }
					    }
					});
				},1000)
			},
			// item条长按结束
			itemTouchEnd(e){
				e.preventDefault();
				clearTimeout(timers)
				timers = null
			},
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
	}
	.Dir-item{
		padding: 20rpx;
		background-color: #eeeeee;
		border-bottom: solid 1px #fff;
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	.Dir-item-icon{
		height:80rpx;
		width: 80rpx;
		margin-right: 40rpx;
	}
	.Dir-item-txt{
		display: flex;
		flex-direction: column;
		flex: 1;
	}
</style>
